import 'dart:convert';

import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import 'package:badges/badges.dart';

import '../../blocs/cart.dart';
import '../../blocs/helper.dart';
import '../../blocs/product.dart';
import '../../blocs/menu.dart';
import '../../blocs/helper.dart';
import '../../util/app_util.dart';
import 'comp_category_list.dart';
import '../../util/_initwork.dart';
import 'package:fluwx/fluwx.dart';

class OrderHomeScreen extends StatefulWidget {
  OrderHomeScreen({Key? key}) : super(key: key);
  _OrderHomeScreenState createState() => _OrderHomeScreenState();
}

class _OrderHomeScreenState extends State<OrderHomeScreen> with AfterLayoutMixin<OrderHomeScreen> {
  late Offset cartOffset;

  late ProductBloc listSourceRepository;
  late HelperBloc lb_helper;

  GlobalKey cartKey = GlobalKey();
  GlobalKey rootKey = GlobalKey();

  GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
  ValueChanged _onChanged = (val) => print(val);

  @override
  void afterFirstLayout(BuildContext context) {
    if ((AppSession.appUtil.popup_window['popup_title'] ?? '')
        .isNotEmpty) if (AppSession.popupFlag == false) {
      showDialog(context: context, builder: (_) => _popup_ads(context));
      AppSession.popupFlag = true;
    }
  }

  _login(BuildContext context) {
    App.router.navigateTo(context, AppRoutes.loginSignin);
  }

  _cancel() {}

  @override
  void initState() {
    super.initState();

    lb_helper = context.read<HelperBloc>();

    Provider.of<ProductBloc>(context, listen: false).getHomeCategory();
    listSourceRepository = new ProductBloc();
    listSourceRepository.criteria = {
      "category_id": "",
    };
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      if(cartKey.currentContext?.findRenderObject()!=null){
        RenderBox renderBox = cartKey.currentContext?.findRenderObject() as RenderBox;
        cartOffset = renderBox.localToGlobal(Offset.zero);
        AppSession.homeCart = cartOffset;
      }

      Provider.of<CartBloc>(context, listen: false).loadStorage();
      if (lb_helper.addr.isEmpty) lb_helper.addrUpdate(AppSession.userAddr);
    });
    AppSession.homeRoot = rootKey;
  }

  @override
  void dispose() {
    listSourceRepository.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // var lv_loc_str = '选择配送地址';
    // if ((AppSession.userAddr ?? {}).isNotEmpty) if ((AppSession.userAddr['addr'] ?? '').isNotEmpty)
    //   lv_loc_str = AppSession.userAddr['addr'];
    var ll_banners = [];
    if ((AppSession.appUtil.data['home_data'] ?? {}).isNotEmpty)
      ll_banners = AppSession.appUtil.data['home_data']['banner'];

    return Material(
      color: Colors.white,
      child: LoadingMoreCustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            elevation: 0.0,
            automaticallyImplyLeading: false,
            backgroundColor: Color(0xffFF3434),
            brightness: Brightness.light,
            pinned: true,
            title: Container(
              key: rootKey,
              child: Column(
                children: <Widget>[
                  // HomeCartBlock(iv_key: test),

                  Container(
                    margin: EdgeInsets.only(right: 22.w, top: 18.w, bottom: 8.w),
                    // padding: EdgeInsets.all(0.w), left: 22.w,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        TextButton(
                          child: Container(
                            child: Row(//左边点击选择配送地址
                              children: <Widget>[
                                Icon(
                                  // MaterialCommunityIcons.map_marker_radius,
                                  Icons.account_circle_rounded,
                                  color: Colors.white,
                                  size: 32,
                                ),
                                Container(
                                  padding: EdgeInsets.only(left: 2.w),
                                  width: 160.w,
                                  child: Consumer<HelperBloc>(
                                    builder: (context, _helper, child) =>
                                        Builder(builder: (context) {
                                      return Text(
                                        ((_helper.addr['addr'] ?? '').isNotEmpty)
                                            ? _helper.addr['addr']
                                            : '选择配送地址',
                                        softWrap: true,
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 15.sp,
                                        ),
                                      );
                                    }),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          onPressed: () async {
                            if ((AppSession.authortoken ?? '').isEmpty)
                              AppPopupService.showAlertSimple(
                                'I',
                                '请先登录',
                                '',
                                iv_cancel_text: '先不了',
                                cancel: _cancel,
                                iv_confirm_text: '去登录',
                                confirm: _login(context),
                              );
                            else
                              App.router.navigateTo(context, AppRoutes.accountAddrList);
                          },
                        ),
                        Container(
                          child: Consumer<CartBloc>(
                            builder: (context, _cart, child) => Builder(
                              builder: (context) {
                                return GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    if (_cart.amount == 0)
                                      AppPopupService.showAlertSimple(
                                          'I', '购物车是空的', '请先选择商品加入购物车，然后再结账哦');
                                    else
                                      App.router.navigateTo(context, AppRoutes.orderCart);
                                  },
                                  child: Badge(
                                    badgeColor: Colors.red,
                                    toAnimate: true,
                                    shape: BadgeShape.circle,
                                    borderRadius: BorderRadius.circular(20),
                                    animationType: BadgeAnimationType.scale,
                                    child: Image.asset(
                                      'assets/order/cart_circle.png',
                                      key: cartKey,
                                    ),
                                    badgeContent: Text(_cart.amount.toString(),
                                        style: TextStyle(color: Colors.white)),
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          SliverPersistentHeader(
            pinned: true,
            floating: false,
            delegate: _SliverAppBarDelegate(
              maxHeight: 50.h,
              minHeight: 10.h,
              child: Container(
                color: Color(0xffFF3434),
                height: 50.h,
                width: 338.w,
                padding: EdgeInsets.symmetric(
                  horizontal: 25.w,
                  vertical: 0.h,
                ),
                child: FormBuilder(
                  // context,
                  key: _fbKey,
                  autovalidateMode: AutovalidateMode.always,
                  initialValue: {
                    'keyword': '',
                  },
                  enabled: true,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(color: AppColor.greyBg),
                      borderRadius: BorderRadius.circular(20.0),
                    ),
                    child: FormBuilderTextField(
                      name: "keyword",
                      autofocus: false,//是否选中输入框
                      decoration: InputDecoration(
                        hintText: "请输入想要的产品",
                        // contentPadding: EdgeInsets.all(10.0),
                        border: InputBorder.none,
                        suffixIcon: Container(
                          width: 70.w,
                          margin: EdgeInsets.symmetric(vertical: 0.h, horizontal: 0.w),
                          decoration: BoxDecoration(
                            color: AppColor.yellowMain,
                            borderRadius: BorderRadius.all(Radius.circular(20.0)),
                          ),
                          child: TextButton(
                            onPressed: () async {
                              FocusScope.of(context).requestFocus(FocusNode());
                              _fbKey.currentState?.save();

                              if ((_fbKey.currentState?.value['keyword'] ?? '').isNotEmpty) {
                                var lm_param = {
                                  "keyword": _fbKey.currentState?.value['keyword'],
                                };
                                var lv_param = Uri.encodeQueryComponent(jsonEncode(lm_param));
                                App.router.navigateTo(context, '/product_list?param=${lv_param}');
                              } else {
                                AppPopupService.showAlertSimple('I', '注意啦', '产品关键词不能为空',
                                    iv_duration: Duration(seconds: 3));
                              }
                            },
                            style: ButtonStyle(
                              overlayColor: MaterialStateColor.resolveWith((states) => Color(0x55FF8A80)),
                              //shadowColor: Color(0x99FF8A80),
                            ),
                            // highlightColor: const Color(0x55FF8A80),
                            // splashColor: const Color(0x99FF8A80),
                            child: Text(
                              '搜索',
                              style: TextStyle(color: AppColor.blackMain),
                            ),
                          ),
                        ),
                        prefixIcon: Icon(Icons.search, color: AppColor.yellowMain),
                      ),
                      onChanged: _onChanged,
                      // valueTransformer: (text) => num.tryParse(text),
                      // validators: [],
                      keyboardType: TextInputType.text,
                    ),
                  ),
                ),
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildListDelegate(
              [
                Stack(
                  alignment: Alignment.topCenter,
                  children: <Widget>[
                    Container(
                      height: 80.h,
                      decoration: BoxDecoration(
                        color: Color(0xffFF3434),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
                      height: 160.h,
                      width: 343.w,
                      child: Swiper(
                        key: ObjectKey(ll_banners),
                        autoplay: true,
                        autoplayDelay: 3000,
                        viewportFraction: 0.99999,
                        itemCount: ll_banners.length,
                        itemBuilder: (BuildContext context, int index) {
                          var _currentBanner;
                          if (ll_banners.isEmpty) {
                            _currentBanner = [];
                          } else {
                            _currentBanner = (ll_banners.length != 0) ? ll_banners[index] : [];
                          }
                          return ClipRRect(
                            borderRadius: BorderRadius.circular(6),
                            child: GestureDetector(
                              onTap: () {
                                try {
                                  switch (ll_banners[index]
                                      ['banner_navitype']) {
                                    case 2:
                                      // final flutterWebViewPlugin =  new FlutterWebviewPlugin();
                                      // flutterWebViewPlugin.close();
                                      var encodedUrl = Uri.encodeComponent(
                                          ll_banners[index]['banner_url']);
                                      App.router.navigateTo(
                                          context, '/webview/${encodedUrl}');
                                      break;
                                    case 21:
                                      launchWeChatMiniProgram(
                                      username: "gh_474ce27a7b9f",
                                      path: '/pages/lunarpage/lunarpage?areaCode=124');
                                      break;  
                                    case 20:
                                      launchWeChatMiniProgram(
                                      username: "gh_474ce27a7b9f",);
                                      break;    
                                  }
                                } catch (exception, stackTrace) {
                                  print(exception);
                                  print(stackTrace);
                                }
                              },
                              child: CachedNetworkImage(
                                imageUrl: ll_banners[index]['banner_image'],
                                fit: BoxFit.cover,
                              ),
                            ),
                          );
                          // ),
                        },
                        pagination: new SwiperPagination(
                          builder: SwiperPagination.dots,
                        ),
                        control: new SwiperControl(
                          color: Colors.transparent,
                        ),
                      ),
                    ),
                  ],
                ),

                //-------- Adding here ---------//
                Container(
                  color: Colors.white,
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(top: 5.h),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            _categoryComp(
                                AppSession.appUtil.category_list[0]['category_id'],
                                AppSession.appUtil.category_list[0]['name'],
                                AppSession.appUtil.category_list[0]['image_url']),
                            _categoryComp(
                                AppSession.appUtil.category_list[1]['category_id'],
                                AppSession.appUtil.category_list[1]['name'],
                                AppSession.appUtil.category_list[1]['image_url']),
                            _categoryComp(
                                AppSession.appUtil.category_list[2]['category_id'],
                                AppSession.appUtil.category_list[2]['name'],
                                AppSession.appUtil.category_list[2]['image_url']),
                            _categoryComp(
                                AppSession.appUtil.category_list[3]['category_id'],
                                AppSession.appUtil.category_list[3]['name'],
                                AppSession.appUtil.category_list[3]['image_url']),
                            _categoryComp(
                                AppSession.appUtil.category_list[4]['category_id'],
                                AppSession.appUtil.category_list[4]['name'],
                                AppSession.appUtil.category_list[4]['image_url']),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  color: Colors.white,
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(top: 5.h),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            _categoryComp(
                                AppSession.appUtil.category_list[5]['category_id'],
                                AppSession.appUtil.category_list[5]['name'],
                                AppSession.appUtil.category_list[5]['image_url']),
                            _categoryComp(
                                AppSession.appUtil.category_list[6]['category_id'],
                                AppSession.appUtil.category_list[6]['name'],
                                AppSession.appUtil.category_list[6]['image_url']),
                            _categoryComp(
                                AppSession.appUtil.category_list[7]['category_id'],
                                AppSession.appUtil.category_list[7]['name'],
                                AppSession.appUtil.category_list[7]['image_url']),
                            // _categoryComp(
                            //     AppSession.appUtil.category_list[8]['category_id'],
                            //     AppSession.appUtil.category_list[8]['name'],
                            //     AppSession.appUtil.category_list[8]['image_url']),
                            _categoryComp(
                                0,
                                (AppSession.wholesale_wh_id != 0) ? '个人零售!' : '团购批发!',
                                (AppSession.wholesale_wh_id != 0)
                                    ? 'assets/homepage/home_icon_familysale.png'
                                    : 'assets/homepage/home_icon_wholesale.png'),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Provider.of<ProductBloc>(context, listen: true).promo_list.isNotEmpty
                    ? Padding(
                        padding: EdgeInsets.only(top: 26.h),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            CategoryItemComponent(
                                iv_category_id: 0,
                                iv_name: '限时抢购!',
                                iv_list: Provider.of<ProductBloc>(context, listen: true).promo_list)
                          ],
                        ),
                      )
                    : Container(),
                Container(
                  height: Provider.of<ProductBloc>(context, listen: true).home_cate.length * 327.h,
                  child: ListView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    itemCount:
                        Provider.of<ProductBloc>(context, listen: true).home_cate.length,
                    itemBuilder: (BuildContext context, int index) {
                      var _item = Provider.of<ProductBloc>(context, listen: true).home_cate[index];
                      return Padding(
                        padding: EdgeInsets.only(bottom: 26.h),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            CategoryItemComponent(
                                iv_category_id: _item['category_id'],
                                iv_name: _item['category_name'],
                                iv_list: _item['prods'])
                          ],
                        ),
                      );
                    },
                  ),
                ),
                Container(
                    margin: EdgeInsets.symmetric(horizontal: 21.w, vertical: 10.h),
                    width: 323.w,
                    height: 86.h,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/homepage/首页分类banner_为您精选.png'),
                        fit: BoxFit.cover,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(43)),
                    ),
                    child: Container(
                        padding: EdgeInsets.only(left: 158.w, top: 27.h),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            AppTextWidget.categoryBannerText('为您精选', Colors.white),
                          ],
                        )))
              ],
            ),
          ),
          LoadingMoreSliverList(
            SliverListConfig<Map>(
              itemBuilder: _OrderHomeScreenState.generateItem,
              sourceList: listSourceRepository,
//                    showGlowLeading: false,
//                    showGlowTrailing: false,
              padding: EdgeInsets.all(0.0),
              // collectGarbage: (List<int> indexes) {
              //   ///collectGarbage
              //   indexes.forEach((index) {
              //     final item = listSourceRepository[index];
              //   });
              // },
              // viewportBuilder: (int firstIndex, int lastIndex) {
              //   // print("viewport : [$firstIndex,$lastIndex]");
              // },
            ),
          ),
        ],
      ),
    );
  }

  Widget _popup_ads(BuildContext context) {
    return Dialog(
      child: Container(
        width: 300.w,
        height: 650.h,
        color: Colors.black54,
        child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                width: 300.w,
                height: 600.h,
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: CachedNetworkImageProvider(
                          AppSession.appUtil.popup_window['image_info']['url'],
                        ),
                        fit: BoxFit.cover)),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context, rootNavigator: true).pop('dialog');
                },
                style: ButtonStyle(
                  padding: MaterialStateProperty.all(EdgeInsets.all(0.0)),
                ),
                // padding: EdgeInsets.all(0.0),
                child: Image.asset('assets/main/close-circle.png'),
              ),
            ]),
      ),
    );
  }

  Widget _categoryComp(int iv_category_id, String iv_category_name, String iv_category_img) {
    var lv_img = 'assets/order/category_default.png';
    var lm_param = {
      "category_id": iv_category_id,
      "category_name": iv_category_name,
    };
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        if (iv_category_id != 0) {
          var res = await Provider.of<MenuBloc>(context, listen: false)
              .fetchSubcategories(iv_category_id);
          if (res['ev_error'] != 0) {
            AppPopupService.showText(res['ev_context']);
          } else {
            App.router.navigateTo(context, AppRoutes.subCategoryList);
          }
        } else {
          App.router.navigateTo(context, AppRoutes.accountSwitch);
        }
      },
      child: Container(//商城头部分类菜单
        height: 100.h,
        width: 60.w,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            if (iv_category_img.isEmpty) Image.asset(lv_img),
            iv_category_id == 0
                ? Image.asset(
                    iv_category_img,
                    fit: BoxFit.cover,
                  )
                : CachedNetworkImage(
                    imageUrl: iv_category_img,
                    fit: BoxFit.cover,
                  ),
            Text(
              iv_category_name,
              style: TextStyle(
                color: iv_category_id != 0 ? AppColor.greyText : Color(0xff149AFC),
                fontSize: 13.sp,
              ),
            ),
          ],
        ),
      ),
    );
  }

  static Widget generateItem(BuildContext context, Map item, int index) {
    late Offset temp;
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          App.router.navigateTo(context, AppRoutes.productDetail + '?prod_id=${item['sku_id']}');
        },
        child: Container(//为您精选下瀑布流
            width: 343.w,
            height: 180.h,
            padding: EdgeInsets.only(left: 20.w, right: 12.w, top: 18.h),
            child: Column(children: [
              Row(
                children: <Widget>[
                  Container(
                    width: 80.w,
                    height: 80.h,
                    margin: EdgeInsets.only(
                      right: 27.w,
                    ),
                    child: CachedNetworkImage(
                      imageUrl: item['image_url'],
                      fit: BoxFit.cover,
                    ),
                  ),
                  Container(
                    width: 225.w,
                    height: 142.h,
                    padding: EdgeInsets.only(
                      left: 12.w,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                            height: 94.h,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Container(
                                    child: Text(
                                      item['sku_name'],
                                      softWrap: true,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: AppColor.nameProduct,
                                        fontWeight: FontWeight.w500,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 4.7.h),
                                  Text(
                                    item['sku_desc'],
                                    softWrap: true,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      color: AppColor.descProduct,
                                      fontWeight: FontWeight.normal,
                                      fontSize: 10.sp,
                                    ),
                                  ),
                                  SizedBox(height: 5.h),
                                  item['outstock_info'] == 1
                                      ? Container(
                                          width: 80.w,
                                          padding: EdgeInsets.symmetric(horizontal: 5.w),
                                          height: 16.h,
                                          decoration: BoxDecoration(
                                            color: Color(0xffFDE3E3),
                                            borderRadius: BorderRadius.circular(2),
                                          ),
                                          child: Center(
                                              child: Text('库存不足',
                                                  style: TextStyle(
                                                    color: Color(0xffFF3434),
                                                    fontSize: 10.sp,
                                                  ))))
                                      : Container(),
                                  Container(
                                    height: 20.h,
                                    child: Text(
                                      '\$' + item['sku_price'] + '/' + item['unit_desc'],
                                      softWrap: true,
                                      maxLines: 1,
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontWeight: FontWeight.normal,
                                        fontSize: 14.sp,
                                      ),
                                    ),
                                  )
                                ])),
                        Row(children: [
                          //   Container(
                          //     height: 47.h,
                          //     width: 110.w,
                          //     child: Column(
                          //         crossAxisAlignment: CrossAxisAlignment.start,
                          //         mainAxisAlignment: MainAxisAlignment.start,
                          //         children: [
                          //           SizedBox(height: 8.h),
                          //           Container(
                          //             height: 14.h,
                          //             child: Text(
                          //               '\$' +
                          //                   item['sku_price'] +
                          //                   '/' +
                          //                   item['unit_desc'],
                          //               softWrap: true,
                          //               maxLines: 1,
                          //               style: TextStyle(
                          //                 color: AppColor.nameProduct,
                          //                 fontWeight: FontWeight.normal,
                          //                 fontSize: 12.sp,
                          //                 decoration: TextDecoration.lineThrough,
                          //               ),
                          //             ),
                          //           ),
                          //           SizedBox(height: 5.h),
                          //           Container(
                          //             height: 20.h,
                          //             child: Text(
                          //               '\$' +
                          //                   item['sku_price'] +
                          //                   '/' +
                          //                   item['unit_desc'],
                          //               softWrap: true,
                          //               maxLines: 1,
                          //               style: TextStyle(
                          //                 color: Colors.red,
                          //                 fontWeight: FontWeight.normal,
                          //                 fontSize: 14.sp,
                          //               ),
                          //             ),
                          //           )
                          //         ]),
                          //   ),
                          SizedBox(width: 80.w),
                          Column(children: [
                            SizedBox(height: 19.h),
                            Container(
                              width: 95.w,
                              height: 28.h,
                              child: Consumer<CartBloc>(
                                builder: (context, _cart, child) => Builder(
                                  builder: (context) {
                                    return Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: <Widget>[
                                        GestureDetector(
                                          onTap: () {
                                            _cart.reduceItem(item['sku_id']);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.minus_circle_outline,
                                            LineIcons.minusCircle,
                                            color: AppColor.nameProduct,
                                            size: 24,
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.symmetric(horizontal: 14.w),
                                          alignment: Alignment.center,
                                          child: Text(
                                            _cart.itemAmount(item['sku_id']).toString(),
                                            style: TextStyle(
                                              color: AppColor.nameProduct,
                                              fontWeight: FontWeight.normal,
                                              fontSize: 20.sp,
                                            ),
                                          ),
                                        ),
                                        GestureDetector(
                                          onPanDown: (details) {
                                            temp = new Offset(details.globalPosition.dx,
                                                details.globalPosition.dy);
                                          },
                                          onTap: () {
                                            late Function callback;
                                            // setState(() {
                                            _cart.addItem(item);
                                            OverlayEntry entry = OverlayEntry(builder: (ctx) {
                                              return ParabolaAnimateWidget(
                                                AppSession.homeRoot,
                                                temp,
                                                AppSession.homeCart,
                                                Icon(
                                                  Icons.add_circle,
                                                  color: Colors.redAccent,
                                                ),
                                                callback,
                                                duration: 800,
                                              );
                                            });

                                            callback = (status) {
                                              if (status == AnimationStatus.completed) {
                                                entry.remove();
                                              }
                                            };

                                            Overlay.of(AppSession.homeRoot.currentContext!)!.insert(entry);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.plus_circle,
                                            LineIcons.plusCircle,
                                            color: AppColor.nameProduct,
                                            size: 24,
                                          ),
                                        ),
                                      ],
                                    );
                                  },
                                ),
                              ),
                            ),
                          ])
                        ])
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 18.h),
              Divider(
                color: Color(0xffcacaca),
                height: 1.0,
                indent: 0.0,
                endIndent: 0.0,
              ),
            ])));
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    required this.minHeight,
    required this.maxHeight,
    required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => this.minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
